package com.ecommerce.controller;

import com.ecommerce.common.ResultBody;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * 文件上传服务
 *
 * @author wang
 */

@RestController
@Api(value = "FileController", tags = {"文件上传接口"})
@RequestMapping("/file")
@Log4j
public class FileController {

    @Value("${fileLocation}")
    private String fileLocation;

    @ApiOperation(value = "文件上传", notes = "文件上传")
    @PostMapping("upload")
    public ResultBody upload(MultipartFile file) throws IOException {
        //本地
//        String realPath = ResourceUtils.getURL("classpath:").getPath() + fileLocation;
        //线上
        String realPath = "/home/" + fileLocation;
        String fileName = fileUpload(realPath, file);
        return ResultBody.ok().data(fileName).message("文件上传成功");
    }

    @ApiOperation(value = "文件下载", notes = "文件下载")
    @GetMapping("download")
    @ResponseBody
    public ResultBody download(String fileName, HttpServletResponse response) throws IOException {
        //本地
//        String realPath = ResourceUtils.getURL("classpath:").getPath() + fileLocation;
        //线上
        String realPath = "/home/" + fileLocation;
        fileDownload(fileName, realPath, response);
        return ResultBody.ok().data(fileName).message("文件下载成功");
    }

    /**
     * 文件上传
     *
     * @param path 文件上传路径
     * @param file 文件
     * @return 文件上传路径
     */
    private String fileUpload(String path, MultipartFile file) {
        String fileName = null;
        try {
            File newFile = new File(path);
            // 如果文件夹不存在、则新建
            if (!newFile.exists()) {
                newFile.mkdirs();
            }
            // 上传
            fileName = (new Date()).getTime() + "@" + file.getOriginalFilename();
            file.transferTo(new File(newFile, fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }

    /**
     * 文件下载
     *
     * @param fileName 文件名称
     */
    private void fileDownload(String fileName, String realPath, HttpServletResponse response) {
        try {
            // 获得文件输入流
            FileInputStream inputStream = new FileInputStream(new File(realPath, fileName));
            // 设置响应头、以附件形式打开文件
            String returnName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            response.setContentType("application/json;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + returnName);
            ServletOutputStream outputStream = response.getOutputStream();
            int len;
            byte[] data = new byte[1024];
            while ((len = inputStream.read(data)) != -1) {
                outputStream.write(data, 0, len);
            }
            outputStream.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
